#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QMimeData>
#include <QDragEnterEvent>
#include <QMessageBox>
#include <QFileInfo>
#include <uiutils.h>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::processUiFile(const QString &filePath)
{
    QString output = UiUtils::removeByCondition(filePath, UiUtils::CR_R_PT());
    if (output.isEmpty()) {
        QMessageBox::information(this, "提示", "处理失败");
        return;
    }

    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        file.write(output.toUtf8());
        file.close();
    }

    QMessageBox::information(this, "提示", "处理完成");
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    // 允许有URI的拖拽操作
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

void MainWindow::dropEvent(QDropEvent *event)
{
    // 提取所有拖入的文件路径
    const QList<QUrl> urls = event->mimeData()->urls();
    if (urls.isEmpty()) return;

    // 取第一个文件的本地路径
    QString filePath = urls.first().toLocalFile();
    QFileInfo file(filePath);

    // 加载文件（根据你的业务逻辑修改）
    if (!filePath.isEmpty() && filePath.endsWith(".ui")) {
        qDebug() << "Dropped file:" << filePath;

        // 实现文件处理逻辑
        auto answer = QMessageBox::question(this, "询问", "是否处理 " + file.fileName() + " 文件?" + QString("(包含%1个可处理部分)").arg(UiUtils::countOccurrences(filePath, UiUtils::CR_R_PT())));
        if (answer == QMessageBox::Yes) {
            processUiFile(filePath);
        }
    }
}

